<template>
  <div class="order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>📋 我的订单</h1>
      <div>
        <el-button type="primary" @click="refreshOrders" icon="Refresh">
          刷新订单
        </el-button>
        <el-button type="success" @click="createOrderFromCart" :disabled="!canCreateOrder">
          从购物车下单
        </el-button>
      </div>
    </div>

    <!-- 订单筛选 -->
    <el-card class="filter-card" v-if="filteredOrders.length > 0">
      <div class="filter-content">
        <span>订单状态：</span>
        <el-radio-group v-model="filterStatus" @change="filterOrders">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="pending">待支付</el-radio-button>
          <el-radio-button label="paid">已支付</el-radio-button>
          <el-radio-button label="completed">已完成</el-radio-button>
          <el-radio-button label="cancelled">已取消</el-radio-button>
        </el-radio-group>
      </div>
    </el-card>

    <!-- 空订单状态 -->
    <el-empty v-if="filteredOrders.length === 0" description="暂无订单">
      <div class="empty-actions">
        <el-button type="primary" @click="$router.push('/')">去点餐</el-button>
        <el-button type="success" @click="createOrderFromCart" :disabled="!canCreateOrder">
          从购物车下单
        </el-button>
      </div>
    </el-empty>

    <!-- 订单列表 -->
    <div v-else>
      <el-card 
        v-for="order in paginatedOrders" 
        :key="order.id" 
        class="order-card"
        :class="{
          'order-pending': order.status === 'pending',
          'order-paid': order.status === 'paid',
          'order-completed': order.status === 'completed',
          'order-cancelled': order.status === 'cancelled'
        }"
      >
        <template #header>
          <div class="order-header">
            <div class="order-info">
              <span class="order-number">订单号：{{ order.orderNumber }}</span>
              <span class="order-time">下单时间：{{ formatTime(order.createTime) }}</span>
            </div>
            <div class="order-status">
              <el-tag 
                :type="getStatusType(order.status)"
                size="large"
              >
                {{ getStatusText(order.status) }}
              </el-tag>
            </div>
          </div>
        </template>

        <!-- 订单商品 -->
        <div class="order-items">
          <div v-for="item in order.items" :key="item.id" class="order-item">
            <el-image 
              :src="item.image || ''" 
              :alt="item.name"
              class="item-image"
              fit="cover"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="item-info">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-price">¥{{ item.price.toFixed(2) }} × {{ item.quantity }}</div>
            </div>
            <div class="item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
          </div>
        </div>

        <el-divider />

        <!-- 订单汇总 -->
        <div class="order-summary">
          <div class="summary-item">
            <span>商品金额：</span>
            <span>¥{{ order.subtotal.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>配送费：</span>
            <span>¥{{ order.deliveryFee.toFixed(2) }}</span>
          </div>
          <div class="summary-item total">
            <span>实付金额：</span>
            <span class="total-amount">¥{{ order.totalAmount.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions">
          <el-button 
            v-if="order.status === 'pending'" 
            type="primary" 
            @click="payOrder(order)"
          >
            立即支付
          </el-button>
          <el-button 
            v-if="order.status === 'pending'" 
            @click="cancelOrder(order)"
          >
            取消订单
          </el-button>
          <el-button 
            v-if="order.status === 'paid'" 
            type="success"
            @click="confirmReceipt(order)"
          >
            确认收货
          </el-button>
          <el-button 
            v-if="order.status === 'completed'" 
            @click="viewOrderDetail(order)"
          >
            查看详情
          </el-button>
          <el-button 
            v-if="order.status !== 'pending'" 
            type="primary" 
            plain
            @click="reorder(order)"
          >
            再次购买
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="filteredOrders.length > pageSize">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="filteredOrders.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 订单数据类型
interface OrderItem {
  id: number
  name: string
  price: number
  quantity: number
  image?: string
  description?: string
}

interface Order {
  id: number
  orderNumber: string
  items: OrderItem[]
  subtotal: number
  deliveryFee: number
  totalAmount: number
  status: 'pending' | 'paid' | 'completed' | 'cancelled'
  createTime: string
  payTime?: string
  completeTime?: string
}

// 数据
const orders = ref<Order[]>([])
const filterStatus = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)

// 计算属性
const filteredOrders = computed(() => {
  let result = orders.value
  
  if (filterStatus.value !== 'all') {
    result = result.filter(order => order.status === filterStatus.value)
  }
  
  // 按时间倒序排序
  result = result.sort((a, b) => 
    new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
  )
  
  return result
})

const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

// 检查购物车是否有商品可以下单
const canCreateOrder = computed(() => {
  const cart = JSON.parse(localStorage.getItem('cart') || '[]')
  return cart.length > 0
})

// 生命周期
onMounted(() => {
  loadOrders()
  // 添加存储事件监听器，实现跨标签页同步
  window.addEventListener('storage', handleStorageChange)
})

onUnmounted(() => {
  window.removeEventListener('storage', handleStorageChange)
})

// 方法
const loadOrders = () => {
  console.log('正在加载订单数据...')
  
  // 从localStorage加载订单数据
  const savedOrders = localStorage.getItem('orders')
  
  if (savedOrders) {
    try {
      orders.value = JSON.parse(savedOrders)
      console.log('加载的订单数据:', orders.value)
    } catch (error) {
      console.error('解析订单数据失败:', error)
      orders.value = [] // 解析失败时设为空数组
    }
  } else {
    console.log('没有订单数据，显示空状态')
    orders.value = [] // 没有数据时设为空数组
  }
}

const saveOrders = () => {
  localStorage.setItem('orders', JSON.stringify(orders.value))
  // 触发自定义事件，通知其他组件订单数据已更新
  window.dispatchEvent(new CustomEvent('ordersUpdated'))
}

// 处理存储变化事件（跨标签页同步）
const handleStorageChange = (e: StorageEvent) => {
  if (e.key === 'orders' && e.newValue) {
    try {
      orders.value = JSON.parse(e.newValue)
      ElMessage.success('订单数据已更新')
    } catch (error) {
      console.error('解析订单数据失败:', error)
    }
  }
}

const filterOrders = () => {
  currentPage.value = 1
}

const refreshOrders = () => {
  loadOrders()
  ElMessage.success('订单已刷新')
}

// 从购物车创建新订单
const createOrderFromCart = async () => {
  try {
    const cart = JSON.parse(localStorage.getItem('cart') || '[]')
    if (cart.length === 0) {
      ElMessage.warning('购物车为空，无法下单')
      return
    }
    
    await ElMessageBox.confirm(
      `确认下单 ${cart.length} 件商品？总金额：¥${calculateCartTotal(cart)}`,
      '确认下单',
      {
        confirmButtonText: '确认下单',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 计算订单金额
    const subtotal = calculateCartSubtotal(cart)
    const deliveryFee = 5 // 固定配送费
    const totalAmount = subtotal + deliveryFee
    
    // 生成新订单
    const newOrder: Order = {
      id: Date.now(),
      orderNumber: `ORD${new Date().getTime()}`,
      items: cart.map((item: any) => ({
        id: item.id,
        name: item.name,
        price: item.price,
        quantity: item.quantity,
        image: item.image,
        description: item.description
      })),
      subtotal,
      deliveryFee,
      totalAmount,
      status: 'pending',
      createTime: new Date().toISOString()
    }
    
    // 添加到订单列表
    orders.value.unshift(newOrder)
    saveOrders()
    
    // 清空购物车
    localStorage.removeItem('cart')
    window.dispatchEvent(new CustomEvent('cartUpdated'))
    
    ElMessage.success('下单成功！请及时支付')
  } catch {
    // 用户取消操作
  }
}

// 计算购物车小计
const calculateCartSubtotal = (cart: any[]) => {
  return cart.reduce((sum: number, item: any) => sum + (item.price * item.quantity), 0)
}

// 计算购物车总金额（含配送费）
const calculateCartTotal = (cart: any[]) => {
  return (calculateCartSubtotal(cart) + 5).toFixed(2)
}

const formatTime = (timeString: string) => {
  return new Date(timeString).toLocaleString('zh-CN')
}

const getStatusType = (status: string) => {
  const types: { [key: string]: string } = {
    pending: 'warning',
    paid: 'success',
    completed: 'info',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: { [key: string]: string } = {
    pending: '待支付',
    paid: '已支付',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || '未知状态'
}

const payOrder = async (order: Order) => {
  try {
    await ElMessageBox.confirm(
      `确认支付订单 ${order.orderNumber}，金额：¥${order.totalAmount.toFixed(2)}？`,
      '确认支付',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    order.status = 'paid'
    order.payTime = new Date().toISOString()
    saveOrders()
    
    ElMessage.success('支付成功！')
  } catch {
    // 用户取消支付
  }
}

const cancelOrder = async (order: Order) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消此订单吗？',
      '取消订单',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '再想想',
        type: 'warning'
      }
    )
    
    order.status = 'cancelled'
    saveOrders()
    
    ElMessage.success('订单已取消')
  } catch {
    // 用户取消操作
  }
}

const confirmReceipt = async (order: Order) => {
  try {
    await ElMessageBox.confirm(
      '确认收到商品了吗？',
      '确认收货',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    order.status = 'completed'
    order.completeTime = new Date().toISOString()
    saveOrders()
    
    ElMessage.success('收货确认成功！')
  } catch {
    // 用户取消操作
  }
}

const viewOrderDetail = (order: Order) => {
  ElMessage.info(`查看订单详情：${order.orderNumber}`)
  // 这里可以跳转到订单详情页面
}

const reorder = (order: Order) => {
  // 将订单商品添加到购物车
  const cart = JSON.parse(localStorage.getItem('cart') || '[]')
  order.items.forEach(item => {
    const existingItem = cart.find((cartItem: any) => cartItem.id === item.id)
    if (existingItem) {
      existingItem.quantity += item.quantity
    } else {
      cart.push({ ...item })
    }
  })
  localStorage.setItem('cart', JSON.stringify(cart))
  window.dispatchEvent(new CustomEvent('cartUpdated'))
  
  ElMessage.success('商品已添加到购物车')
  router.push('/cart')
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}
</script>

<style scoped>
.order-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  color: #303133;
  margin: 0;
  font-size: 28px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.empty-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.order-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-number {
  font-weight: 600;
  font-size: 16px;
}

.order-time {
  font-size: 14px;
  color: #606266;
}

.order-items {
  margin-bottom: 15px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  margin-right: 15px;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  border-radius: 6px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 600;
  margin-bottom: 5px;
}

.item-price {
  color: #606266;
  font-size: 14px;
}

.item-subtotal {
  font-weight: 600;
  color: #e74c3c;
  min-width: 80px;
  text-align: right;
}

.order-summary {
  margin-bottom: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.summary-item.total {
  font-weight: 600;
  font-size: 16px;
  margin-top: 10px;
}

.total-amount {
  color: #e74c3c;
  font-size: 18px;
}

.order-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 订单状态样式 */
.order-pending {
  border-left: 4px solid #e6a23c;
}

.order-paid {
  border-left: 4px solid #67c23a;
}

.order-completed {
  border-left: 4px solid #909399;
}

.order-cancelled {
  border-left: 4px solid #f56c6c;
}
</style>